public class demo1 {
    public static String longestCommonPrefix(String[] strs) {
        if(strs.length<2)return strs[0];
        String temp=find(strs[0], strs[1]);
        for(int i=2;i<strs.length;i++) {
            temp=find(strs[i], temp);
        }
        return temp;
    }
    public static String find(String s1,String s2) {
        int x=Math.min(s1.length(),s2.length());
        for(int i=0;i<x;i++) {
            if(s1.charAt(i)!=s2.charAt(i)) {
                return s1.substring(0,i);
            }
        }
        if(s1.length()<=s2.length())
            return s1;
        else return s2;
    }
    public static void main(String[] args) {
        String[]arr={"dog","racecar","car"};
        String s=longestCommonPrefix(arr);
        System.out.println(s);
    }
    public static String longestCommonPrefix1(String[] strs) {
        if(strs.length<2)return strs[0];
        for(int i=0;i<strs[0].length();i++) {
            for(int j=1;j<strs.length;j++) {
                //这里是i==strs[j].length()时就已经越界访问
                if(i==strs[j].length()||strs[0].charAt(i)!=strs[j].charAt(i)) {
                    return strs[0].substring(0,i);
                }
            }
        }
        return strs[0];
    }
}
